<?php
/**
 * Created by PhpStorm.
 * User: Sky
 * Date: 17/4/25
 * Time: 下午1:17
 */

namespace app\models;

use app\librarys\DbCacheUtility;

use app\models\Permission;

/**
 * 系统菜单
 * Class Menu
 * @package app\models
 */
class Menu
{
    const SessionKey = 'session_key_menu';
    const SessionMenuStatus = 'session_menu_status'; // 0-收缩 1-展开

    private static function _loopMenu($parent_id)
    {
        $data = self::_getMenuList($parent_id);
        if (!$data) return null;
        foreach ($data as &$val) {
            $val['sub_menu_list'] = self::_loopMenu($val['id']);
        }
        return $data;
    }

    /**
     * 获取系统菜单,按父子结构输出。只输出当前登录用户的有权限访问的菜单。
     * @return mixed
     */
    public static function getAllMenus()
    {
        if(!YII_DEBUG) {
            if (\Yii::$app->session->has(self::SessionKey) == true) {
                return \Yii::$app->session->get(self::SessionKey);
            }
        }
        $menuList = self::_loopMenu('0');

        // 将菜单根据当前用户权限处理相应数据,将无权限的菜单移除
        $menuCount = count($menuList);
        for ($menuIndex = 0; $menuIndex < $menuCount; $menuIndex++) {
            $menu = &$menuList[$menuIndex];
            if (isset($menu['sub_menu_list'])) {
                $subMenuCount = count($menu['sub_menu_list']);
                for ($i = 0; $i < $subMenuCount; $i++) {
                    $subMenu = &$menu['sub_menu_list'][$i];
                    if (isset($subMenu['controller']) && isset($subMenu['action'])) {
                       if (!Permission::hasPermission($subMenu['controller'], $subMenu['action'])) {
                           unset($menu['sub_menu_list'][$i]);
                       }
                    }
                }
            }
            if (isset($menu['controller']) && isset($menu['action']) && $menu['controller'] != '' && $menu['action'] != '' && $menu['controller'] != null && $menu['action'] != null) {
               if (!Permission::hasPermission($menu['controller'], $menu['action'])) {
                   unset($menuList[$menuIndex]);
               }
            } else if (!(isset($menu['sub_menu_list']) && count($menu['sub_menu_list']) > 0)) {
                unset($menuList[$menuIndex]);
            }
        }


        \Yii::$app->session->remove(self::SessionKey);
        if (Manager::getCurrentManager() != null) {  // fixed by sky(如果session过期后,session中的manager为空,导致所有菜单都无权限访问。已知session过期后再登陆时菜单为空。)
            \Yii::$app->session->set(self::SessionKey, $menuList);
        }
        $menuList_arr = array_values($menuList);
        foreach ($menuList_arr as &$value) {
            if (isset($value['sub_menu_list'])) {
                $value['sub_menu_list'] = array_values($value['sub_menu_list']);
            }
        }

//        var_dump($menuList_arr);exit;

        $i = 0;
        foreach ($menuList_arr as $menuList){
            if($menuList['name'] == '小程序'){
                break;
            }
            $i = $i + 1;
        }

        //获取当前登录人员的小程序列表
        $current_mananger_mini_programs = Manager::getCurrentManager()['mini_programs'];
        foreach ($current_mananger_mini_programs as $mini_program){
            $mini_program_menu = $menuList_arr[$i];
            $mini_program_menu['name'] = $mini_program['name'];
            $mini_program_menu['sub_menu_list'] = self::modifySubMenuList($mini_program_menu['sub_menu_list'],$mini_program['id']);
            array_push($menuList_arr,$mini_program_menu);
        }
        unset($menuList_arr[$i]);
        $menuList_arr = array_values($menuList_arr);

        return $menuList_arr;

    }

    /**
     * 修改小程序的submenulist
     * @param $sub_menu_list
     */
    private static function modifySubMenuList(&$sub_menu_list,$mini_program_id)
    {
        foreach ($sub_menu_list as &$sub_menu) {
            if ($sub_menu['action']) {
                $sub_menu['action'] = $sub_menu['action'] . '?' . 'mini_program_id=' . $mini_program_id;
            }

            if(count($sub_menu['sub_menu_list'])>0){
                self::modifySubMenuList($sub_menu['sub_menu_list'],$mini_program_id);
            }
        }

        return $sub_menu_list;
    }

    private static function _getMenuList($parentId)
    {
        $cmd = \Yii::$app->db->createCommand('SELECT * FROM t_menu WHERE parent_id=:parentId AND is_deleted=0 AND is_enabled=1 ORDER BY sort');
        $cmd->bindValue(':parentId', $parentId);
        return DbCacheUtility::queryAll($cmd, DbCacheUtility::NoCacheTime, false);
    }


    /**
     * 获取系统所有菜单，用来编辑菜单情况
     * @return mixed
     */
    public static function getAllSystemMenus()
    {
        $data = [];
        self::_getSystemMenuList($data, '0', 1);
        return $data;
    }

    /**
     * @param $data
     * @param $parentId
     * @param $level
     */
    private static function _getSystemMenuList(&$data, $parentId, $level)
    {
        $sql = 'SELECT * FROM t_menu WHERE  parent_id =:parentId  AND  is_deleted =0  ORDER BY sort';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':parentId', $parentId);
        $results = DbCacheUtility::queryAll($cmd);

        foreach ($results as $result) {
            $result['level'] = $level;
            array_push($data, $result);
            self::_getSystemMenuList($data, $result['id'], $level + 1);
        }
    }


    /**
     * 根据id获取菜单
     * @param $id
     * @return array|false|null
     */
    public static function getMenuById($id)
    {
        $sql = 'SELECT * FROM t_menu WHERE id = :id';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':id', $id);

        $result = DbCacheUtility::queryOne($cmd);
        if ($result == false) {
            return null;
        }
        return $result;
    }

    /**
     * 根据id获取菜单
     * @param $parent_id
     * @return array|false|null
     */
    public static function getMenuByParentId($parent_id)
    {
        $sql = 'SELECT * FROM t_menu WHERE parent_id = :parent_id';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':parent_id', $parent_id);

        $result = DbCacheUtility::queryAll($cmd);
        if ($result == false) {
            return null;
        }
        return $result;
    }

    /**
     * 保存菜单
     * @param $id
     * @param $league_id
     * @param $parent_id
     * @param $name
     * @param $controller
     * @param $action
     * @param $icon
     * @param $sort
     * @return bool
     */
    public static function saveMenu($id, $parent_id, $name, $controller, $action, $icon, $sort, $is_enabled)
    {
        $cmd = \Yii::$app->db->createCommand('call p_menu_save(:id,:parent_id,:name,:controller,:action,:icon,:sort,:is_enabled)');
        $cmd->bindValue(':id', $id);
        $cmd->bindValue(':parent_id', $parent_id);
        $cmd->bindValue(':name', $name);
        $cmd->bindValue(':controller', $controller);
        $cmd->bindValue(':action', $action);
        $cmd->bindValue(':icon', $icon);
        $cmd->bindValue(':sort', $sort);
        $cmd->bindValue(':is_enabled', $is_enabled);

        return DbCacheUtility::queryScalar($cmd);
    }


    /**
     * 删除菜单
     * @param $id
     * @return bool
     */
    public static function deleteMenu($id)
    {
        $transaction = \Yii::$app->db->beginTransaction();
        $result = 0;
        try {
            //删除本身菜单
            $cmd = \Yii::$app->db->createCommand(self::_getDeleteSql());
            $cmd->bindValue(':id', $id);
            DbCacheUtility::execute($cmd);
            //删除子菜单
            self::_deleteAllChildIds($id);
            $transaction->commit();
            $result = 1;
        } catch (\Exception $ex) {
            $transaction->rollBack();
        }
        return $result > 0;
    }

    /**
     * 删除所有的子菜单
     * @param $parentId
     * @return bool
     */
    private static function _deleteAllChildIds($parentId)
    {
        $cmd = \Yii::$app->db->createCommand(
            'SELECT `id` FROM t_menu WHERE is_deleted =0 AND parent_id =:parentId');
        $cmd->bindValue(':parentId', $parentId);
        //子节点集合
        $ids = DbCacheUtility::queryAll($cmd);
        foreach ($ids as $id) {
            $cmd = \Yii::$app->db->createCommand(self::_getDeleteSql());
            $cmd->bindValue(':id', $id['id']);
            DbCacheUtility::execute($cmd);
            self::_deleteAllChildIds($id['id']);
        }
        return true;
    }

    /**
     * 获取删除菜单sql
     * @return string
     */
    private static function _getDeleteSql()
    {
        return 'UPDATE t_menu SET is_deleted = 1 WHERE id =:id ;';
    }


    public static function getUrlForInit($obj, $url)
    {
        $url_for_node = '';
        if (isset($obj['sub_menu_list'])) {
            $length = count($obj['sub_menu_list']) - 1;
            for ($i = $length; $i >= 0; $i--) {
                $url_for_node = self::getUrlForInit($obj['sub_menu_list'][$i], $url);
            }
        } else {
            return "{$url}/{$obj['controller']}/{$obj['action']}";
        }
        return $url_for_node;
    }

    public static function modifyMenuStatus($content_width)
    {
        if (!\Yii::$app->session->has(self::SessionMenuStatus)) {
            \Yii::$app->session->set(self::SessionMenuStatus, [
                'status' => 0,
                'content_width' => null
            ]);
        }

        $session_menu_status = \Yii::$app->session->get(self::SessionMenuStatus);
        $session_menu_status['status'] = 1 - $session_menu_status['status'];
        $session_menu_status['content_width'] = $content_width;


        \Yii::$app->session->set(self::SessionMenuStatus, $session_menu_status);
    }
}